function setPredictPayDate(objEnddate, days){
    var dt = new Date(parseInt($dp.cal.getP('y')), parseInt($dp.cal.getP('M'))-1, parseInt($dp.cal.getP('d'))+days);
    objEnddate.value = dt.format("yyyy-MM-dd");
}        

$(document).ready(function(){
	try{
		$.jgrid.no_legacy_api = true;
		$.jgrid.useJSON = true;
		$.jgrid.formatter.integer.thousandsSeparator = ',';
		$.jgrid.formatter.number.thousandsSeparator = ',';
		$.jgrid.formatter.currency.thousandsSeparator = ',';
		$("#orderItemsTable").jqGrid({						
			url : appRoot + '/orderItem/list/' + orderId + '?ajax=1',
			editurl : appRoot + '/orderItem/save?ajax=1&orderId=' +orderId,
			datatype : 'json',
			mtype : 'GET',
			jsonreader: {             
				repeatitems: false,
				id:'Id',
				root:'rows'
			}, 
			colNames : [ 'id','objectId','销售编号', '数量','单位','描述', '单价', '小计'],
			colModel : [ 
		   {
				name : 'id',
				index : 'id',
				editable : true,
				hidden:true
				
			}, {
				name : 'objectId',
				index : 'objectId',
				editable : true,
				hidden:true
			},
			{
				name : 'customerPurchaseNo',
				index : 'customerPurchaseNo',
				width : 120,
				align : 'left',
				resizable : false,
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true
				}
		
			}, {
				name : 'quantity',
				index : 'quantity',
				width : 60,
				editable : true,
				align : 'right',
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}
			}, {
				name : 'unit',
				index : 'unit',
				width : 50,
				editable : true,
				edittype:'select',
				formatter:'select',
				editoptions : {
			        value :units
			    },
				editrules : {
					required : true
				}
			}, {
				name : 'productDecription',
				index : 'productDecription',
				width : 280,
				editable : true,
				edittype:'textarea',
				editoptions:{
					cols:21,rows:3
				},
				sortable: false,
				editrules : {
					required : true
				}
			}, {
				name : 'unitPrice',
				index : 'unitPrice',
				width : 80,
				align : 'right',
				editable : true,
				edittype:'text',
				sortable: false,
				editrules : {
					required : true,
					number : true
				}							
			}, {
				name : 'amount',
				index : 'amount',
				width : 100,
				align : 'right',
				editable : false,
				sortable: false,
				editrules : {
					number : true
				}
			}
			],
			gridComplete: function(){
				var grid = $("#orderItemsTable");
				sum = grid.jqGrid('getCol', 'amount', false, 'sum'); 
				grid.jqGrid('footerData','set', {customerPurchaseNo:"合计:", amount: sum}); 
			},
			width: 730,
			height : 300,
			pager : $('#pager'),
			nowNum : 100,
			rowNum : 100,
			sortname : 'id',
			viewrecords : true,
			footerrow: true,
			shrinkToFit:false,
			caption : '订单明细'
		}).navGrid("#pager",{edit:orderEditable,add:orderEditable,del:orderEditable,search:false});
		
		$("#orderChargesTable").jqGrid({                       
		    url : appRoot + '/orderCharge/list/' + orderId + '?ajax=1',
		    editurl : appRoot + '/orderCharge/save?ajax=1&orderId=' +orderId,
		    datatype : 'json',
		    mtype : 'GET',
		    jsonreader: {             
		        repeatitems: false,
		        id:'Id',
		        root:'rows'
		    }, 
		    
		    colNames : [ 'id','objectId','收费项目', '金额'],
		    colModel : [
		   {
		        name : 'id',
		        index : 'id',
		        editable : true,
		        hidden:true
		        
		    }, {
		        name : 'objectId',
		        index : 'objectId',
		        editable : true,
		        hidden:true
		    },
		    {
		        name : 'chargeName',
		        index : 'chargeName',
		        width : 300,
		        align : 'left',
		        resizable : false,
		        editable : true,
		        edittype:'textarea',
		        editoptions:{
		            cols:21,rows:3
		        },
		        sortable: false,
		        editrules : {
		            required : true
		        }
		
		    }, {
		        name : 'charge',
		        index : 'charge',
		        width : 100,
		        align : 'right',
		        editable : true,
		        edittype:'text',
		        sortable: false,
		        editrules : {
		            required : true,
		            number : true
		        }
		    }
		    ],
		    gridComplete: function(){
		        var grid = $("#orderChargesTable");
		        sum = grid.jqGrid('getCol', 'charge', false, 'sum'); 
		        grid.jqGrid('footerData','set', {chargeName:"合计:", charge: sum}); 
		    },
		    width: 730,
		    height : 150,
		    pager : $('#pager2'),
		    nowNum : 100,
		    rowNum : 100,
		    sortname : 'id',
		    viewrecords : true,
		    footerrow: true,
		    caption : '额外费用明细'
		}).navGrid("#pager2",{edit:orderEditable,add:orderEditable,del:orderEditable,search:false});
		
	}catch(e){}
	
	$(".colorbox").colorbox({iframe:true, innerWidth:700, innerHeight:460});

	$(".picture").colorbox();
});

   fileLimit = 3;
   function createUploader(){
       var filelimituploader = new qq.FileUploader({
       element: $('#filelimit-fine-uploader')[0],
       action: appRoot + '/picture/upload/2/' + orderId + '?ajax=1',
       debug: false,
       demoMode: false,
       forceMultipart:true,
       allowedExtensions: ['jpeg', 'jpg', 'gif', 'png'],
       sizeLimit: fileUploadSize,
       uploadButtonText:"上传图片",
       cancelButtonText:"取消",
       failUploadText:"上传失败",
       onSubmit: function(id, fileName) {
    	   orderfileCount ++;
           if(orderfileCount > fileLimit) {
               alert("已经达到最大上传文件数量，不能再上传了！");
               orderfileCount--;
               return false;
           }
       },
       onCancel: function(id, fileName) {
    	   orderfileCount--;
           if(orderfileCount <= fileLimit) {
               $('#filelimit-fine-uploader .qq-upload-button').show();
           }
       },
       onComplete: function(id, fileName, responseJSON) {
           if (responseJSON.success) {
               var fileId = responseJSON.fileId;
               var fileSuffix = responseJSON.fileSuffix;
               var fileName = responseJSON.fileName;
               $('#filelimit-fine-uploader').append('<div style="float: left;width: 200px;" id="d_f_' + fileId + '"><a href="' + appRoot + '/download/' 
                        + fileId + fileSuffix + '" title="' + fileName + '" class="picture"><img alt="' + fileName + '" src="' + appRoot + '/download/'
                        + fileId + fileSuffix + '" width="150">'
                        + '<a href="javascript:deletePicture(\'' + fileId + '\')">删除</a></div>');
               $(".picture").colorbox();
           }
       }
   });
   $(".qq-upload-list").hide();
   }
   
   function deletePicture(fileId){
       if(fileId){
           if(confirm("你确定要删除此图片吗？")){
           $.ajax({
                url: appRoot + "/picture/delete/" + fileId + "?ajax=1",
                type:'post',
                dataType:'json',
                success:function(msg){
                    if(msg.success){
                        alert("删除成功");
                        orderfileCount--;
                        $("#d_f_" + fileId).remove();
                        }
                    }
               });
           }
       }
   }
   
 //Pagge
	function getCustomer(id){
		$("#suberror").hide();
		$("#subnotice").hide();
		$("#otherUsers").val("");
		$("input[type='checkbox']").each(function(){
            $(this).attr("checked",false);
        });
		if(id){
			$.ajax({
                 url: appRoot + "/customer/get/" + id,
                 type:'post',
                 dataType:'json',
                 success:function(msg){
                     $("#customer_2").text(msg.entity.name).attr("title",msg.entity.email);
                 }
            });
		}
	}
	
	function notify(){
		if(currentOrderId==null){
			return;
		}
        $(".audit").attr("disabled",true);
        $("#notifyButton").attr("disabled",true);
        var selected = getCheckedValuesString(document.getElementsByName("users"));
        var customer = ($("#customer_1").attr("checked")=="checked");
        var others = $("#otherUsers").val();
        if(!selected&&!customer&&!others){
        	$("#suberror").html("请至少选择一个接收者").show();
        	$(".audit").attr("disabled",false);
            $("#notifyButton").attr("disabled",false);
        }else{
        	$("#suberror").hide();
        	$("#subnotice").html("操作进行中...").show();
        	$.ajax({
                 url: appRoot + "/order/notify/" + currentOrderId + "?date=" + (new Date()).valueOf(),
                 type:'post',
                 dataType:'json',
                 data:'purchasers=' + (selected==null?"":selected) + "&customer=" + customer + "&others=" + others,
                 success:function(msg){
                     if(msg.result){
                         showMessage("邮件已发送");
                     }else{
                         showMessage("操作失败");
                     }
                     $(".audit").attr("disabled",false);
                     $("#notifyButton").attr("disabled",false);
                     jQuery.fn.colorbox.close();
                 }
            });
        }
        
    }
	
	function audit(orderId,action){
		$("#notice").html("操作进行中...").show();
		$(".audit").attr("disabled",true);
		$.ajax({
	         url: appRoot + "/order/audit/" + orderId,
	         type:'post',
	         dataType:'json',
	         data:"status=20" ,
	         success:function(msg){
	        	 if(msg.result){
	        		 window.location.href= appRoot +'/order/' + action + '?message=' + encodeURIComponent('操作成功');
	        	 }else{
	        		 $("#notice").html("").hide();
	        		 showMessage("操作失败");
	        		 $(".audit").attr("disabled",false);
	        	 }
	         }
		});
	}
	
	
	function backward(action){
		if(currentOrderId==null){
			return;
		}
		var reason = $("#reason").val();
        if(!reason){
        	$("#suberror1").html("请填写退回原因").show();
        	return;
        }
		$("#subnotice1").html("操作进行中...").show();
		$("#suberror1").html("").hide();
		$(".bacward").attr("disabled",true);
		$("#backwardButton").attr("disabled",true);
		$.ajax({
	         url: appRoot + "/order/backward/" + currentOrderId + "?reason=" +  encodeURIComponent(reason) + "&date=" + (new Date()).valueOf(),
	         type:'post',
	         dataType:'json',
	         success:function(msg){
	        	 if(msg.result){
	        		 window.location.href= appRoot +'/order/' + action + '?message=' + encodeURIComponent('操作成功');
	        	 }else{
	        		 var message = msg.message;
	        		 if(message==null){
	        			 message = "操作失败";
	        		 }
	        		 $("#subnotice1").html("").hide();
	        		 $("#suberror1").html(message).show();
	        		 $(".bacward").attr("disabled",false);
	        		 $("#backwardButton").attr("disabled",false);
	        	 }
	         }
		});
	}
	
	function pay(orderId,action){
        $(".audit").attr("disabled",true);
        if(confirm("你确认收到货款？")){
        	$.ajax({
                url: appRoot + "/order/pay/" + orderId,
                type:'post',
                dataType:'json',
                success:function(msg){
                    if(msg.result){
                        window.location.href= appRoot + '/order/' + action + '?message=' + encodeURIComponent('操作成功');
                    }else{
                        showMessage("操作失败");
                        $(".audit").attr("disabled",false);
                    }
                }
           });
        }
    }
	
	function finish(orderId,action){
        $(".audit").attr("disabled",true);
        if(confirm("你确认定单已完成？")){
            $.ajax({
                url: appRoot + "/order/finish/" + orderId,
                type:'post',
                dataType:'json',
                success:function(msg){
                    if(msg.result){
                        window.location.href= appRoot + '/order/' + action + '?message=' + encodeURIComponent('操作成功');
                    }else{
                        showMessage("操作失败");
                        $(".audit").attr("disabled",false);
                    }
                }
           });
        }else{
        	$(".audit").attr("disabled",false);
        }
    }